#include <iostream>
#include <string.h>
#include "client.h"

// Default constructor; sets server host name to local machine and
// port to the default.
//
Client::Client() :
    m_fd(0),
    m_port(kDefaultPort)
{
    if (gethostname(m_hostname, MAXHOSTNAMELEN - 1) != 0)
    {
        std::cout << "Error: Unable to get host name. Exiting program.\n";
        exit(1);
    }
}

// Constructor takes in hostname and port
//
Client::Client(const char* hostname, const short port) :
    m_fd(0),
    m_port(port)
{
    strcpy(m_hostname, hostname);
}

// Destructor cleans up socket
//
Client::~Client()
{
    if (m_fd != 0)
    {
        close(m_fd);
    }
}

// Establish connection to server
//
bool Client::open()
{
    sockaddr_in addr;   // server
    memset(&addr, 0, sizeof(sockaddr_in));
    
    addr.sin_family = AF_INET;
    addr.sin_port = htons(m_port);

    m_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (m_fd != -1)
    {
        struct hostent* pHE = gethostbyname(m_hostname);
        if (pHE != NULL)
        {
            memcpy(&addr.sin_addr, pHE->h_addr_list[0], pHE->h_length);
            if (connect(m_fd, (sockaddr*) &addr, sizeof(addr)) == 0)
            {
                return true;
            }
        }
    }
    
    return false;
}

// Sends a command to the server
//
bool Client::send(const char* cmd)
{
    int n = write(m_fd, cmd, strlen(cmd));    
    return n == strlen(cmd);
}

// Receives output from server; simply display on screen
//
bool Client::receive(bool mutter)
{
    char buffer[256];
    int  len = sizeof(buffer);
    
    memset(buffer, '\0', sizeof(buffer));
    
    int n = 0;
    while ((n = read(m_fd, buffer, len - 1)) > 0)
    {
        if (mutter)
        {
            std::cout << buffer;
        }
        memset(buffer, '\0', len);
    }
    
    return true;
}

